package com.caiheng.api.controller.estate;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.asymmetric.AsymmetricManager;
import com.alipay.api.internal.util.asymmetric.IAsymmetricEncryptor;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.dto.EstateRoomDto;
import com.caiheng.api.entity.dto.FeeListTemplateDto;
import com.caiheng.api.entity.dto.VisitorInfoDto;
import com.caiheng.api.entity.estate.*;
import com.caiheng.api.entity.platform.Parameter;
import com.caiheng.api.entity.platform.SmsTemplate;
import com.caiheng.api.entity.sys.SysDept;
import com.caiheng.api.entity.sys.SysUser;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.service.estate.*;
import com.caiheng.api.service.platfom.ParameterService;
import com.caiheng.api.service.platfom.SmsTemplateService;
import com.caiheng.api.service.sys.SysConfigService;
import com.caiheng.api.service.sys.SysDeptService;
import com.caiheng.api.service.sys.SysUserService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 *@Author: ZhouWei
 *@Description:  小区相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/estate")//url:模块/资源/{}/细分
public class EstateController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private EstateService estateService;
    @Resource
    private EstateUserService estateUserService;
    @Resource
    private PropertyUserService propertyUserService;
    @Resource
    private EstateRoomService estateRoomService;
    @Resource
    private EstateRoomBangUserService roomBangUserService;
    @Resource
    private PropertyFeeOrderTemplateService feeOrderTemplateService;
    @Resource
    private EstateCustomerCallRecordService estateCustomerCallRecordService;
    @Resource
    private SysConfigService sysConfigService;
    @Resource
    private SysDeptService sysDeptService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private EstateWorkLogService estateWorkLogService;
    @Resource
    private PaySlipService paySlipService;
    @Resource
    private ParameterService parameterService;

    @Resource
    private EstateVisitRecordService estateVisitRecordService;

    @Resource
    protected RedisTemplate<String, Object> redisTemplate;
    @Resource
    private SmsTemplateService smsTemplateService;
    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址

    @Value("${web.imgPrefixOss}")
    private String imgPrefix;//图片地址


    @Value("${web.spiPublicKey}")
    private String spiPublicKey;//

    @Value("${web.spiPrivateKey}")
    private String spiPrivateKey;//


    /**
     * 小区详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail")
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int estate_id = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(user.getEstateId() == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定社区"),true,true);
            }

            Estate estate = estateService.findById(estate_id);
            if(estate == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该社区不存在"),true,true);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("estate",estate);
            map.put("integral",user.getIntegral());

            String diKouRate = sysConfigService.selectConfigByKey("sys.integral_rate");
            map.put("diKouRate",Integer.parseInt(diKouRate));

            List<EstateRoomDto> roomsList = estateRoomService.getEstateRoomList(estate_id);

            map.put("roomsList",roomsList);


            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * spi 回调数据
     * @param
     * @throws Exception
     */
    @PostMapping(value="/spi/notify")
    public String spiNotify(@RequestParam Map<String, Object> requestParam) throws Exception{
        JSONObject result = null;
        try{
//            logBefore(logger, "spi/notify 接收的参数： "+requestParam);
            JSONObject jsonObject = JSONUtil.parseObj(requestParam);
            System.out.println("spi/notify 接收的参数： " + jsonObject.toString());


            String bizContent = jsonObject.getStr("biz_content");
            JSONObject bizContentJson = JSONUtil.parseObj(bizContent);
            String utc_timestamp = jsonObject.getStr("utc_timestamp");

            String formData = bizContentJson.getStr("formData");
            String visitorInfo = bizContentJson.getStr("visitorInfo");


            String formStr = null;
//            // 使用私钥,对formData进行解密
            String cipherFormDataStr = "";
            if (StrUtil.isNotBlank(formData)) {
                try {
                    System.out.println("表单数据：formData: " + formData);
                    formStr = encryptor().decrypt(formData, StandardCharsets.UTF_8.name(), spiPrivateKey);
                    System.out.println("解密后的表单内容:  "+ formStr);
                } catch (AlipayApiException e) {
                    // 表单数据解密异常
                    e.printStackTrace();
                }

                JSONObject form = JSONUtil.parseObj(formStr);
                System.out.println("表单内容(Map): " + form);

            }

            // 对访客信息解密
            String visitorInfoStr = null;
            try {
                visitorInfoStr = encryptor().decrypt(visitorInfo, StandardCharsets.UTF_8.name(), spiPrivateKey);
                System.out.println("解密后的访客身份内容:{}"+  visitorInfoStr);
            } catch (AlipayApiException e) {
                // 表单数据解密异常
                e.printStackTrace();
            }
            if (StrUtil.isNotBlank(visitorInfoStr)) {
                VisitorInfoDto visitorInfoDto = JSONUtil.toBean(visitorInfoStr, VisitorInfoDto.class);
                System.out.println("访客身份DTO: " + visitorInfoDto);
            }


            int ret = estateVisitRecordService.addRecord(formStr, visitorInfoStr, bizContent, utc_timestamp);


        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return "Ok";
    }

    /**
     * spi 回调数据
     * @param
     * @throws Exception
     */
    @PostMapping(value="/spi/notify/test")
    public JSONObject spiNotifyTest(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
//            logBefore(logger, "spi/notify 接收的参数： "+requestParam);
            JSONObject jsonObject = JSONUtil.parseObj(requestParam);
            System.out.println("spi/notify 接收的参数： " + jsonObject.toString());


            String bizContent = jsonObject.getStr("biz_content");

            String utc_timestamp = jsonObject.getStr("utc_timestamp");
            JSONObject bizContentJson = JSONUtil.parseObj(bizContent);

            String formData = bizContentJson.getStr("formData");
            String visitorInfo = bizContentJson.getStr("visitorInfo");



//            // 使用私钥,对formData进行解密
            String cipherFormDataStr = "";
            if (StrUtil.isNotBlank(formData)) {
                String formStr = null;
                try {
                    System.out.println("表单数据：formData: " + formData);
                    formStr = encryptor().decrypt(formData, StandardCharsets.UTF_8.name(), spiPrivateKey);
                    System.out.println("解密后的表单内容:  "+ formStr);
                    JSONObject form = JSONUtil.parseObj(formStr);
                    System.out.println("表单内容(json): " + form);
                } catch (AlipayApiException e) {
                    // 表单数据解密异常
                    e.printStackTrace();
                }


            }

            // 对访客信息解密
            String visitorInfoStr = null;
            try {
                visitorInfoStr = encryptor().decrypt(visitorInfo, StandardCharsets.UTF_8.name(), spiPrivateKey);
                System.out.println("解密后的访客身份内容:{}"+  visitorInfoStr);
            } catch (AlipayApiException e) {
                // 表单数据解密异常
                e.printStackTrace();
            }
            if (StrUtil.isNotBlank(visitorInfoStr)) {
                VisitorInfoDto visitorInfoDto = JSONUtil.toBean(visitorInfoStr, VisitorInfoDto.class);
                System.out.println("访客身份DTO: " + visitorInfoDto);
            }

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 门禁访客信息列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/visit/record")
    public JSONObject visitRecordList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("estate/visit/record 接收的参数： "+requestParam);
            logBefore(logger, "estate/visit/record 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int estate_id = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            estate_id = sysUser.getEstateId();
//            QueryWrapper<SysDept> qwDept = new QueryWrapper<>();
//            qwDept.eq("event_type", 2);
//            qwDept.eq("estate_id", estate_id);
//            qwDept.eq("del_flag", 0);
//            qwDept.last("limit 1");
//            SysDept sysDept = sysDeptService.getOne(qwDept);
            Map<String, Object> mapParam = new HashMap<>();
            mapParam.put("estateId", estate_id);
            mapParam.put("eventType", 2);

            List<SysDept> deptList = sysDeptService.selectDeptListByEstateAndEventType(mapParam);
            if(CollUtil.isEmpty(deptList)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无查询权限"),true,true);
            }
            List<Integer> deptIdList = new ArrayList<>();
            for (SysDept sysDept : deptList) {
                deptIdList.add(sysDept.getDeptId());
            }


            QueryWrapper<EstateUser> qwUser = new QueryWrapper<>();
            qwUser.eq("estate_id", estate_id);
            qwUser.eq("sys_user_id", sysUser.getUserId());
            qwUser.in("dept_id", deptIdList);
            qwUser.last("limit 1");
            EstateUser estateUser = estateUserService.getOne(qwUser);
            if(estateUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无查询权限"),true,true);
            }

            Map<String,Object> map = new HashMap<>();
            QueryWrapper<EstateVisitRecord> qw = new QueryWrapper<>();
            if(StrUtil.isNotEmpty(keyword)){
                qw.and(wrapper->{
                    wrapper.like("mobile", keyword)
                            .or().like("nick_name", keyword)
                            .or().like("scene_name", keyword)
                            .or().like("visit_type", keyword)
                            .or().like("real_name", keyword);
                });
            }
            qw.eq("estate_id", estateUser.getEstateId());
            qw.orderByDesc("id");
            List<EstateVisitRecord> visitRecordList = estateVisitRecordService.getPageEntityList(qw, pageIndex, pageSize);
            for (EstateVisitRecord estateVisitRecord : visitRecordList){

                if(estateUser.getIsManager() == 0){
                    if(StrUtil.isNotEmpty(estateVisitRecord.getMobile())){
                        estateVisitRecord.setMobile(estateVisitRecord.getMobile().substring(0,3) + "****" + estateVisitRecord.getMobile().substring(7,11));
                    }
                }


                if(StrUtil.isNotEmpty(estateVisitRecord.getFormData())){
                    String formDataContent = "";
                    List<String> formData = ListUtil.getListValueContentByJson(estateVisitRecord.getFormData());
                    for (String s : formData) {
                        formDataContent += s + " ";
                    }
                    estateVisitRecord.setFormDataList(formData);
                    estateVisitRecord.setFormDataContent(formDataContent);
                }
            }
            map.put("recordList",visitRecordList);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功", visitRecordList.size(), map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }






    /**
     * 初始密码器
     *
     * @return
     */
    IAsymmetricEncryptor encryptor() {
        try {
            return AsymmetricManager.getByName("RSA2");
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 小区详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/picker/detail")
    public JSONObject pickerDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/picker/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int estate_id = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;

            Map<String,Object> map = new HashMap<>();
            List<EstateRoomDto> roomsList = estateRoomService.getEstateRoomList(estate_id);
            map.put("roomsList",roomsList);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 发送验证码
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/sendCode")
    public JSONObject sendValidateCode(@RequestBody String requestParam) throws Exception {
        JSONObject result = null;
        try {
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int estate_id = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;
            String phoneNum = jsonRequest.containsKey("phoneNum") ? jsonRequest.getStr("phoneNum") : null;
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : null;

            if (!phoneNum.equals("") && phoneNum.length() == 11) {

                long roomBandCount = estateRoomService.getUnBandRoom(user_id,estate_id,phoneNum);
                if(roomBandCount == 0){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无可绑定房屋，请联系物业中心"),true,true);
                }

                SmsTemplate sms = smsTemplateService.selectByUniqueColumn("sms_type",1);
                if(sms == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "发送失败"), true, true);
                }

                Integer smsType = 1;
                if(platform.equals("wxmini")){
                    smsType = 1;
                }else if(platform.equals("wxwork")){
                    smsType = 2;
                }
                //验证码
                int code = Tools.getRandomNum();//生成6位随机数
                String responseCode = smsTemplateService.sendSmsByPhoneCode(String.valueOf(code),phoneNum, smsType);
                if(responseCode.equals("OK")) {
                    redisTemplate.opsForValue().set(phoneNum, code, 900L, TimeUnit.SECONDS);
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"发送成功"),true,false);
                } else {
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"验证码发送失败，请重试"),true,true);
                }
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"请输入正确的手机号"),true,true);
            }
        }catch(Exception e){
            e.printStackTrace();
            System.out.println(""+e.getMessage());
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"系统异常"),true,true);
        }
        return result;
    }

    /**
     * 绑定房屋
     * @param
     * @throws Exception
     */
    @PostMapping(value="/bandRoom")
    public JSONObject bandRoom(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/bandRoom 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int estate_id = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;
            String phoneNum = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num") : null;
//            String code = jsonRequest.containsKey("code") ? jsonRequest.getStr("code") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

//            Parameter parameter = parameterService.getParameterById(1);

            if(StrUtil.isEmpty(phoneNum)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"手机号不能为空"),true,true);
            }

            Estate estate = estateService.findById(estate_id);
            if(estate == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该小区不存在"),true,true);
            }

            if(estate.getState() == 1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂未开放该功能"),true,true);
            }

//            if(parameter.getIsNeedSmsBandRoom() == 1){
//                if(StrUtil.isEmpty(code)){
//                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"验证码不能为空"),true,true);
//                }
//
//                if (code.length() != 6) {
//                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"验证码必须为6位"),true,true);
//                }

                //取出所有有关该手机号的短信验证码
//                if(redisTemplate.opsForValue().get(phoneNum) == null){
//                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请重新获取验证码"),true,true);
//                }

//                String phoneCode = redisTemplate.opsForValue().get(phoneNum).toString();
//                if (StrUtil.isEmpty(phoneCode)) {
//                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"短信验证失败"),true,true);
//                }
//            }


            QueryWrapper<EstateRoom> qwRoom = new QueryWrapper<>();
            qwRoom.select("id");
            qwRoom.eq("estate_id",estate_id);
            qwRoom.like("phone_num",phoneNum);
            long roomCount = estateRoomService.count(qwRoom);
            if(roomCount == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无该手机号绑定信息"),true,true);
            }

            long roomBandCount = estateRoomService.getUnBandRoom(user_id,estate_id,phoneNum);
            if(roomBandCount == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无可绑定信息"),true,true);
            }


            int ret = estateRoomService.bandRoomByPhoneNum(user_id,estate_id,phoneNum,user);
            if(ret > 0){
                redisTemplate.delete(phoneNum);
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"绑定成功"),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"绑定失败"),true,false);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 绑定房屋( 不用手机号绑定 )
     * @param
     * @throws Exception
     */
    @PostMapping(value="/bandRoomNoPhone")
    public JSONObject bandRoomNoPhone(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/bandRoom 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int estate_id = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;
            int roomId = jsonRequest.containsKey("room_id") ? jsonRequest.getInt("room_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            Estate estate = estateService.findById(estate_id);
            if(estate == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该小区不存在"),true,true);
            }

            if(estate.getState() == 1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂未开放该功能"),true,true);
            }

            EstateRoom estateRoom = estateRoomService.findById(roomId);
            if(estateRoom == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该户不存在"),true,true);
            }

            EstateRoomBangUser bangUser = roomBangUserService.getBandUser(user_id,roomId);
            if(bangUser != null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您已绑定该户"),true,true);
            }

            int ret = estateRoomService.bandRoomByNoPhone(user_id,estate_id,roomId);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"绑定成功"),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"绑定失败"),true,false);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 解绑房屋
     * @param
     * @throws Exception
     */
    @PostMapping(value="/unBandRoom")
    public JSONObject unBandRoom(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/bandRoom 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int room_id = jsonRequest.containsKey("room_id") ? jsonRequest.getInt("room_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            EstateRoomBangUser estateRoomBangUser = roomBangUserService.getBandUser(user_id,room_id);
            if(estateRoomBangUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定该房屋"),true,true);
            }

            boolean bl = roomBangUserService.removeById(estateRoomBangUser.getId());
            if(bl){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"解绑成功"),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"绑定失败"),true,false);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  小区列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/list")
    public JSONObject list(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            List<String> estate_names = new ArrayList<>();
            List<Estate> estates = estateService.selectListByColumn("state",0);
            if(estates != null){
                for (Estate estate : estates){
                    estate_names.add(estate.getEstateName());
                }
            }
            Map<String,Object> map = new HashMap<>();
            map.put("estates",estates);
            map.put("estate_names",estate_names);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",estates.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  我的房屋列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/room/list")
    public JSONObject roomList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/room/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            Map<String,Object> map = new HashMap<>();
            map.put("band_count",0);
            List<String> estate_names = new ArrayList<>();
            List<EstateRoom> estateRooms = estateRoomService.getRoomListByUserId(user_id,keyword);
            if(estateRooms != null){
                for (EstateRoom room : estateRooms){
                    estate_names.add(room.getEstateName() + " " + room.getRoomNo());

                    String realName = room.getRealName();
                    if(StrUtil.isNotEmpty(realName)){
                        realName = realName.substring(0,1) + "**";
                        room.setRealName(realName);
                    }

                    String phone_num = room.getPhoneNum();
                    if(StrUtil.isNotEmpty(phone_num) && phone_num.length() >= 11){
                        phone_num = PhoneUtils.hideMiddleFourDigits(phone_num);//phone_num.substring(0,3) + "****" + phone_num.substring(phone_num.length() - 4,phone_num.length());
                        room.setPhoneNum(phone_num);
                    }

                }
                map.put("band_count",estateRooms.size());
            }
            map.put("rooms",estateRooms);
            map.put("room_names",estate_names);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",estateRooms.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  管理员查看管理小区的 房屋列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/admin/room/list")
    public JSONObject roomAdminList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/admin/room/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 20;
            int estate_id = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;

            String keyWord = jsonRequest.containsKey("keyWord") ? jsonRequest.getStr("keyWord") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(estate_id == 0){
                EstateUser estateUser = estateUserService.getEstateUser(user_id);
                if(estateUser == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无查询权限"),true,true);
                }
                estate_id = estateUser.getEstateId();
            }else{
                EstateUser estateUser = estateUserService.getEstateByUser(user_id, estate_id);
                if(estateUser == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无查询权限"),true,true);
                }
            }


            Map<String,Object> map = new HashMap<>();
            List<String> estate_names = new ArrayList<>();
            QueryWrapper<EstateRoom> qw = new QueryWrapper<>();
            qw.eq("estate_id",estate_id);
            if(StrUtil.isNotEmpty(keyWord)){
                qw.and(wrapper->{
                    wrapper.like("phone_num", keyWord)
                            .or().like("real_name",keyWord)
                            .or().like("room_no",keyWord);
                });
            }
            List<EstateRoom> estateRooms = estateRoomService.getPageEntityList(qw,pageIndex,pageSize);
            if(estateRooms != null){
                for (EstateRoom room : estateRooms){

                    QueryWrapper<PropertyFeeOrderTemplate> qwOrder = new QueryWrapper<>();
                    qwOrder.eq("room_id", room.getId());
                    qwOrder.eq("state", 0);
                    qwOrder.last("limit 1");
                    qwOrder.orderByAsc("year_num, month_num");
                    PropertyFeeOrderTemplate orderTemplate = feeOrderTemplateService.getOne(qwOrder);
                    if(orderTemplate != null){
                        room.setLastUnPayTemplate(orderTemplate);
                    }


                    estate_names.add(room.getEstateName() + " " + room.getRoomNo());

                    String realName = room.getRealName();
                    if(StrUtil.isNotEmpty(realName)){
                        realName = realName.substring(0,1) + "**";
                        room.setRealName(realName);
                    }

                    String phone_num = room.getPhoneNum();

                    if(StrUtil.isNotEmpty(phone_num)){
                        String[] phoneArray = phone_num.split("/");
                        if(phone_num.contains("/")){
                            phoneArray = phone_num.split("/");
                        } else if(phone_num.contains(" ")){
                            phoneArray = phone_num.split(" ");
                        } else if(phone_num.contains(",")){
                            phoneArray = phone_num.split(",");
                        }

                        List<String > phoneList = new ArrayList<>();
                        for (String phone : phoneArray) {
                            if(StrUtil.isNotEmpty(phone)){
                                phoneList.add(phone);
                            }
                        }
                        room.setPhoneNumList(phoneList);

                        phone_num = PhoneUtils.hideMiddleFourDigits(phone_num);//.substring(0,3) + "****" + phone_num.substring(phone_num.length() - 4,phone_num.length());
                        room.setPhoneNum(phone_num);

                    }

                    QueryWrapper<EstateCustomerCallRecord> qwCallRecord = new QueryWrapper<>();
                    qwCallRecord.eq("room_id", room.getId());
                    //状态 0 - 待处理  1 - 跟进中  2 - 处理完成
                    qwCallRecord.in("state", 0,1);
                    long count = estateCustomerCallRecordService.count(qwCallRecord);
                    room.setCallRecordCount(count);
                }
            }
            map.put("rooms",estateRooms);
            map.put("room_names",estate_names);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",estateRooms.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  抄表人员看到的 管理小区的 房屋列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/check/room/list")
    public JSONObject checkRoomList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/admin/room/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 20;
//            int estate_id = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;

            String keyWord = jsonRequest.containsKey("keyWord") ? jsonRequest.getStr("keyWord") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            //查询 抄表人员
            EstateUser estateUser  = estateUserService.getEstateUser(user_id);
            if(estateUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }


            Estate estate = estateService.findById(estateUser.getEstateId());
            if(estate == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该小区不存在"),true,true);
            }

            Map<String,Object> map = new HashMap<>();
            List<String> estate_names = new ArrayList<>();
            QueryWrapper<EstateRoom> qw = new QueryWrapper<>();
            qw.eq("estate_id", estateUser.getEstateId());
            if(StrUtil.isNotEmpty(keyWord)){
                qw.and(wrapper->{
                    wrapper.like("phone_num",keyWord).or().like("real_name",keyWord).or().like("room_no",keyWord);
                });
            }
            qw.orderByAsc("room_no");
            List<EstateRoom> estateRooms = estateRoomService.getPageEntityList(qw,pageIndex,pageSize);
            if(estateRooms != null){
                for (EstateRoom room : estateRooms){
                    estate_names.add(room.getEstateName() + " " + room.getRoomNo());

                    String realName = room.getRealName();
                    if(StrUtil.isNotEmpty(realName)){
                        realName = realName.substring(0,1) + "**";
                        room.setRealName(realName);
                    }

                    String phone_num = room.getPhoneNum();
                    phone_num = phone_num.substring(0,3) + "****" + phone_num.substring(phone_num.length() - 4,phone_num.length());
                    room.setPhoneNum(phone_num);


                    room.setIsHasThisMonthWater(0);
                    room.setIsHasThisMonthElectric(0);

                    QueryWrapper<PropertyFeeOrderTemplate> qwWater = new QueryWrapper<>();
                    qwWater.eq("room_no", room.getRoomNo());
                    qwWater.eq("fee_type", "water");
                    qwWater.eq("year_num", estate.getCheckMeterYear());
                    qwWater.eq("month_num", estate.getCheckMeterMonth());
                    qwWater.eq("estate_id", room.getEstateId());
                    qwWater.eq("is_garage", 0);
                    qwWater.last("limit 1");
                    PropertyFeeOrderTemplate templateWater = feeOrderTemplateService.getOne(qwWater);
                    if(templateWater!=null){
                        room.setIsHasThisMonthWater(1);
                    }

                    QueryWrapper<PropertyFeeOrderTemplate> qwElectric = new QueryWrapper<>();
                    qwElectric.eq("room_no", room.getRoomNo());
                    qwElectric.eq("fee_type", "eletrict");
                    qwElectric.eq("year_num", estate.getCheckMeterYear());
                    qwElectric.eq("month_num", estate.getCheckMeterMonth());
                    qwElectric.eq("estate_id", room.getEstateId());
                    qwElectric.eq("is_garage", 0);
                    qwElectric.last("limit 1");
                    PropertyFeeOrderTemplate templateElectric = feeOrderTemplateService.getOne(qwElectric);
                    if(templateElectric!=null){
                        room.setIsHasThisMonthElectric(1);
                    }
                }
            }
            map.put("rooms",estateRooms);
            map.put("room_names",estate_names);

            map.put("is_set_time",0);
            if(estate.getCheckMeterYear()!=null && estate.getCheckMeterMonth()!=null){
                map.put("is_set_time",1);
            }
            map.put("check_time", estate.getCheckMeterYear() + "年" + estate.getCheckMeterMonth() + "月");
//            map.put("check_month",estate.getCheckMeterMonth());

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",estateRooms.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  上传添加抄表数据
     * @param
     * @throws Exception
     */
    @PostMapping(value="/room/template/info")
    public JSONObject getRoomTemplate(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;

        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/admin/room/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int roomId = jsonRequest.containsKey("room_id") ? jsonRequest.getInt("room_id") : 0;
            String fee_type = jsonRequest.containsKey("fee_type") ? jsonRequest.getStr("fee_type") : null;
            int is_garage = jsonRequest.containsKey("is_garage") ? jsonRequest.getInt("is_garage") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            //查询 抄表人员
            EstateUser estateUser  = estateUserService.getEstateUser(user_id);
            if(estateUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }

            EstateRoom estateRoom = estateRoomService.findById(roomId);
            if(estateRoom == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该户不存在"),true,true);
            }

            Estate estate = estateService.findById(estateRoom.getEstateId());
            if(estate == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该小区不存在"),true,true);
            }

            PropertyFeeOrderTemplate waterTemp = feeOrderTemplateService.getLastTemplateInfo(roomId,"water",is_garage);
            map.put("waterTemp",waterTemp);

            PropertyFeeOrderTemplate electricTemplate = feeOrderTemplateService.getLastTemplateInfo(roomId,"eletrict",is_garage);
            map.put("electricTemplate",electricTemplate);


            map.put("roomType", estateRoom.getRoomType());
            //房屋类型  0 - 高层 1 - 低层 2- 商业 3 - 别墅 4 - 其他
            if(estateRoom.getRoomType() == 0){
                map.put("roomTypeTxt", "高层");
            } else if(estateRoom.getRoomType() == 1){
                map.put("roomTypeTxt", "低层");
            } else if(estateRoom.getRoomType() == 2){
                map.put("roomTypeTxt", "商业");
            } else if(estateRoom.getRoomType() == 3){
                map.put("roomTypeTxt", "别墅");
            } else if(estateRoom.getRoomType() == 4){
                map.put("roomTypeTxt", "其他");
            }

            map.put("estateName",estateRoom.getEstateName());
            map.put("roomNo",estateRoom.getRoomNo());

            map.put("check_year",estate.getCheckMeterYear());
            map.put("check_month",estate.getCheckMeterMonth());

            map.put("waterSinglePrice",estate.getWaterSinglePrice());
            map.put("waterBusinessSinglePrice",estate.getWaterBusinessSinglePrice());

            map.put("electricSinglePrice",estate.getElectricSinglePrice());
            map.put("electricBusinessSinglePrice",estate.getElectricBusinessSinglePrice());


            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  上传添加抄表数据
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add/room/template")
    public JSONObject addRoomTemplate(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println( "estate/add/room/template 接收的参数： "+requestParam);
            logBefore(logger, "estate/admin/room/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

//            int estate_id = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;
            int roomId = jsonRequest.containsKey("room_id") ? jsonRequest.getInt("room_id") : 0;

            double year_num = jsonRequest.containsKey("year_num") ? jsonRequest.getInt("year_num") : 0;
            double month_num = jsonRequest.containsKey("month_num") ? jsonRequest.getInt("month_num") : 0;

            double begin_count = jsonRequest.containsKey("begin_count") && StrUtil.isNotEmpty(jsonRequest.getStr("begin_count"))  ? jsonRequest.getDouble("begin_count") : 0d;
            double end_count = jsonRequest.containsKey("end_count")  && StrUtil.isNotEmpty(jsonRequest.getStr("end_count")) ? jsonRequest.getDouble("end_count") : 0d;

            String fee_type = jsonRequest.containsKey("fee_type") ? jsonRequest.getStr("fee_type") : null;
            int is_garage = jsonRequest.containsKey("is_garage") ? jsonRequest.getInt("is_garage") : 0;


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }


            if(StrUtil.isEmpty(fee_type)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请选择抄表类型"),true,true);
            }

            //查询 抄表人员
            EstateUser estateUser  = estateUserService.getEstateUser(user_id);
            if(estateUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }

            EstateRoom estateRoom = estateRoomService.findById(roomId);
            if(estateRoom == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该户不存在"),true,true);
            }

            Estate estate = estateService.findById(estateRoom.getEstateId());
            if(estate == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该小区不存在"),true,true);
            }


            boolean blIsNew = true;
            QueryWrapper<PropertyFeeOrderTemplate> qw = new QueryWrapper<>();
            qw.eq("room_no", estateRoom.getRoomNo());
            qw.eq("fee_type", fee_type);
            qw.eq("year_num", year_num);
            qw.eq("month_num", month_num);
            qw.eq("estate_id", estateRoom.getEstateId());
            qw.eq("is_garage", is_garage);
            qw.last("limit 1");
            PropertyFeeOrderTemplate template = feeOrderTemplateService.getOne(qw);
            if (template == null) {
                template = new PropertyFeeOrderTemplate();
            }else{
                blIsNew = false;
            }

            template.setYearNum(year_num+"");
            template.setMonthNum(month_num+"");
            template.setRoomType(estateRoom.getRoomType());
            template.setEstateId(estateRoom.getEstateId());
            template.setEstateName(estateRoom.getEstateName());
            template.setFeeType(fee_type);
            template.setRoomId(estateRoom.getId());
            template.setRoomNo(estateRoom.getRoomNo());
            template.setPhoneNum(estateRoom.getPhoneNum());
            template.setRealName(estateRoom.getRealName());

            template.setBangWxUserId(0);
            template.setRemark(template.getRemark());
            template.setIsBand(0);
            template.setState(0);
            template.setCreateTime(new Date());
            template.setPaidPrice(new BigDecimal(0));

            if (StrUtil.isNotEmpty(estateRoom.getRoomArea())) {
                template.setRoomArea(Double.parseDouble(estateRoom.getRoomArea()));
            }
            template.setBeginCount(new BigDecimal(begin_count));
            template.setEndCount(new BigDecimal(end_count));
            template.setIsArrears(0);
            template.setIsManualData(1);//手动抄表

            if(fee_type.equals("water")){
                template.setSinglePrice(estate.getWaterSinglePrice());
                //房屋类型  0 - 高层 1 - 低层 2- 商业 3 - 别墅 4 - 其他
                if(estateRoom.getRoomType() == 0 || estateRoom.getRoomType() == 1){
                    template.setSinglePrice(estate.getWaterSinglePrice());
                } else if(estateRoom.getRoomType() == 2){
                    template.setSinglePrice(estate.getWaterBusinessSinglePrice());
                }
            } else if(fee_type.equals("eletrict")){
                template.setSinglePrice(estate.getElectricSinglePrice());
                //房屋类型  0 - 高层 1 - 低层 2- 商业 3 - 别墅 4 - 其他
                if(estateRoom.getRoomType() == 0 || estateRoom.getRoomType() == 1){
                    template.setSinglePrice(estate.getElectricSinglePrice());
                } else if(estateRoom.getRoomType() == 2){
                    template.setSinglePrice(estate.getWaterBusinessSinglePrice());
                }
            }
            System.out.println("===========当前单价： " + template.getSinglePrice() + "====================");

            double useCount = end_count - begin_count;
            template.setPaidCount(new BigDecimal(useCount));

            double totalPrice = MathUtil.getDoubleUp(useCount * template.getSinglePrice().doubleValue()) ;

            template.setTotalPrice(new BigDecimal(totalPrice));

            boolean bl = false;
            if(blIsNew){
                bl = feeOrderTemplateService.save(template);
            }else{
                bl = feeOrderTemplateService.updateById(template);
            }

            if(bl){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"提交成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"提交失败，请重试"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  物业客服所管辖内的 小区列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/admin/list")
    public JSONObject adminList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/admin/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            Map<String,Object> map = new HashMap<>();
            List<Map<String,Object>> estate_names = new ArrayList<>();
            List<Estate> estates = estateService.getEstateListByAdminId(user_id,1);
            if(estates != null){
                for (Estate estate : estates){
                    Map<String,Object> map1 = new HashMap<>();
                    map1.put("text",estate.getEstateName());
                    map1.put("value",estate.getId());
                    estate_names.add(map1);
                }
            }
            map.put("estates",estates);
            map.put("estate_names",estate_names);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",estates.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  我的物业费列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/fee/order/list")
    public JSONObject feeOrderList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "fee/order/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int room_id = jsonRequest.containsKey("room_id") ? jsonRequest.getInt("room_id") : 0;
            String begin_month = jsonRequest.containsKey("begin_month") ? jsonRequest.getStr("begin_month") : DateUtil.getYear() + "-01";
            String end_month = (Integer.parseInt(DateUtil.getYear()) + 1) + "-12";
            String fee_type = jsonRequest.containsKey("fee_type") ? jsonRequest.getStr("fee_type") : "wyf";
            //page - 小程序内页面跳转来的，qrcode - 扫码进来的  admin - 从彩恒云进来的
            String fromType = jsonRequest.containsKey("from_type") ? jsonRequest.getStr("from_type") : "page";

            User user = userService.findById(user_id);
            if(user_id > 0){
                if(user == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
                }
            }

            if(fromType.equals("page")){
                EstateRoomBangUser bangUser = roomBangUserService.getBandUser(user_id,room_id);
                if(bangUser == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该信息不属于您"),true,true);
                }
            }


            EstateRoom estateRoom = estateRoomService.findById(room_id);
            if(estateRoom == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该房屋信息不存在"),true,true);
            }


            String[] endMonthArray = end_month.split("-");

            Integer firstYear = 0;
            Map<String,Object> map = new HashMap<>();

            Estate estate = estateService.findById(estateRoom.getEstateId());
            if(estate!= null){
                map.put("wyfWaterBand",estate.getWyfWaterBand());
            }

            String year = "";
            QueryWrapper<PropertyFeeOrderTemplate> qw = new QueryWrapper<>();
            qw.eq("room_id",room_id);
            qw.eq("state",0);
            qw.last("limit 1");
            qw.orderByAsc("year_num");
            PropertyFeeOrderTemplate templateFirst = feeOrderTemplateService.getOne(qw);
            if(templateFirst!=null){
                map.put("firstYear",templateFirst.getYearNum());
                map.put("endYear", Integer.parseInt(templateFirst.getYearNum()) + 1);
                year = templateFirst.getYearNum();
                if(StrUtil.isEmpty(templateFirst.getYearNum())){
                    year = DateUtil.getYear();
                }
                firstYear = Integer.parseInt(year);
                begin_month = year + "-01";
            }else{
                map.put("firstYear", DateUtil.getYear());
                map.put("endYear", Integer.parseInt(DateUtil.getYear() + 1));
                firstYear = Integer.parseInt(DateUtil.getYear());
                begin_month = DateUtil.getYear() + "-01";
            }

            if(firstYear >= Integer.parseInt(endMonthArray[0])){
                end_month = (firstYear + 1) + "-"+ endMonthArray[1];
            }

            map.put("room",estateRoom);
//            List<FeeOrderTemplateDto> orderTemplates = feeOrderTemplateService.getTemplates(user,room_id,begin_month,end_month);
            List<FeeListTemplateDto> orderTemplates = feeOrderTemplateService.getFeeListTemplates(user,room_id,fee_type,begin_month,end_month);
            map.put("all_templates",orderTemplates);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"获取成功",orderTemplates.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  小区列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/listByCharacters")
    public JSONObject listByCharacters(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/listByCharacters 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int is_band = jsonRequest.containsKey("is_band") ? jsonRequest.getInt("is_band") : 0;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : null;

//            User user = userService.findById(user_id);
//            if(user == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
//            }
            List<Map<String,Object>> estates = new ArrayList<>();
            Map<String,Object> map = new HashMap<>();
            if(is_band == 0){
                estates = estateService.getEstateListByPinyinGroup(keyword);
            }else{
                estates = estateService.getEstateListByUserBand(user_id);
            }
            map.put("estates",estates);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",estates.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  （绑定）根据手机号查询当前手机号所导入的后台管理员账号（仅限于物业人员和 小区工作人员）
     * @param
     * @throws Exception
     */
    @PostMapping(value="/bandUser")
    public JSONObject bandUser(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/bandUser 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int user_type = jsonRequest.containsKey("user_type") ? jsonRequest.getInt("user_type") : 0;
            long sys_user_id = jsonRequest.containsKey("sys_user_id") ? jsonRequest.getLong("sys_user_id") : 0;
            int choose_band_user_id = jsonRequest.containsKey("choose_band_user_id") ? jsonRequest.getInt("choose_band_user_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(sys_user_id);
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该人员账号不存在"),true,true);
            }

            if(sysUser.getStatus().equals("1")){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该账号已禁用"),true,true);
            }

            if(user_type == 2){
                QueryWrapper<PropertyUser> qw = new QueryWrapper<>();
                qw.eq("sys_user_id",sys_user_id);
                qw.last("limit 1");
                PropertyUser propertyUser = propertyUserService.getOne(qw);
                if(propertyUser == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该账号已禁用"),true,true);
                }

                if(propertyUser.getUserId()!=null && propertyUser.getUserId() > 0){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该账号已被其他用户绑定"),true,true);
                }
                propertyUser.setUserId(user_id);
                boolean bl = propertyUserService.updateById(propertyUser);
                if(bl){
//                    user.setSysUserId(sys_user_id);
                    user.setDutySysUserId(sys_user_id);
                    bl = userService.updateById(user);
                    if(bl){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"绑定成功"),true,true);
                    }else {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "绑定失败"), true, true);
                    }
                }else{
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"绑定失败"),true,true);
                }
            } else if(user_type == 3){
                QueryWrapper<EstateUser> qw = new QueryWrapper<>();
                qw.eq("sys_user_id",sys_user_id);
                qw.last("limit 1");
                EstateUser estateUser = estateUserService.getOne(qw);
                if(estateUser == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该账号已禁用"),true,true);
                }

                if(estateUser.getUserId()!=null && estateUser.getUserId() > 0){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该账号已被其他用户绑定"),true,true);
                }
                estateUser.setUserId(user_id);
                boolean bl = estateUserService.updateById(estateUser);
                if(bl){
                    user.setDutySysUserId(sys_user_id);
                    bl = userService.updateById(user);
                    if(bl){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"绑定成功"),true,true);
                    }else {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "绑定失败"), true, true);
                    }
                }else{
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"绑定失败"),true,true);
                }
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无该绑定类型"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  (解绑) 根据手机号查询当前手机号所导入的后台管理员账号（仅限于物业人员和 小区工作人员）
     * @param
     * @throws Exception
     */
    @PostMapping(value="/unBandUser")
    public JSONObject unBandUser(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/unBandUser 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int user_type = jsonRequest.containsKey("user_type") ? jsonRequest.getInt("user_type") : 0;
            int sys_user_id = jsonRequest.containsKey("sys_user_id") ? jsonRequest.getInt("sys_user_id") : 0;
            int choose_band_user_id = jsonRequest.containsKey("choose_band_user_id") ? jsonRequest.getInt("choose_band_user_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(sys_user_id);
            if(sysUser == null) {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该人员账号不存在"),true,true);
            }

            if(sysUser.getStatus().equals("1")) {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该账号已禁用"),true,true);
            }

            if(user_type == 2){
                PropertyUser propertyUser = propertyUserService.findById(choose_band_user_id);
                if(propertyUser == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该绑定信息不存在"),true,true);
                }
                if(propertyUser.getUserId() != null && propertyUser.getUserId().intValue() != user_id){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定该用户"),true,true);
                }
                propertyUser.setUserId(0);
                boolean bl = propertyUserService.updateById(propertyUser);
                if(bl){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"解绑成功"),true,true);
                }else{
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"解绑失败"),true,true);
                }
            } else if(user_type == 3){
                EstateUser estateUser = estateUserService.findById(choose_band_user_id);
                if(estateUser == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该绑定信息不存在"),true,true);
                }
                if(estateUser.getUserId() != null && estateUser.getUserId().intValue() != user_id){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定该用户"),true,true);
                }
                estateUser.setUserId(0);
                boolean bl = estateUserService.updateById(estateUser);
                if(bl){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"解绑成功"),true,true);
                }else{
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"解绑失败"),true,true);
                }
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无该绑定类型"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  根据手机号查询当前手机号所导入的后台管理员账号（仅限于物业人员和 小区工作人员）
     * @param
     * @throws Exception
     */
    @PostMapping(value="/dept/list")
    public JSONObject deptList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/user/list 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }

            Map<String,Object> map = new HashMap<>();
            QueryWrapper<SysDept> qw = new QueryWrapper<>();
            qw.eq("estate_id", sysUser.getEstateId());
            if(StrUtil.isNotEmpty(keyword)){
                qw.like("dept_name", keyword);
            }
            List<SysDept> deptList = sysDeptService.getPageEntityList(qw,pageIndex,pageSize);
            if(CollUtil.isNotEmpty(deptList)){
                for (SysDept dept : deptList){
                    QueryWrapper<EstateUser> qwUser= new QueryWrapper<>();
                    qwUser.eq("dept_id", dept.getDeptId());
                    long userCount = estateUserService.count(qwUser);
                    dept.setUserCount(userCount);
                }
            }
            map.put("deptList",deptList);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",deptList.size(), map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  根据手机号查询当前手机号所导入的后台管理员账号（仅限于物业人员和 小区工作人员）
     * @param
     * @throws Exception
     */
    @PostMapping(value="/user/list")
    public JSONObject userList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/user/list 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int dept_id = jsonRequest.containsKey("dept_id") ? jsonRequest.getInt("dept_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            Map<String,Object> map = new HashMap<>();
            List<EstateUser> estateUsers = estateUserService.selectListByColumn("dept_id", dept_id);
            if(CollUtil.isNotEmpty(estateUsers)){
                for (EstateUser estateUser : estateUsers){
                    SysUser sysUser = sysUserService.findById(estateUser.getSysUserId());
                    if(sysUser != null){
                        estateUser.setPhoneNum(sysUser.getPhoneNum());
                    }
                }
            }

            map.put("estateUsers",estateUsers);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功", estateUsers.size(), map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  工资条信息列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/paySlip/list")
    public JSONObject paySlipList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String, Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/paySlip/list 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            QueryWrapper<PaySlip> qw = new QueryWrapper<>();
            qw.eq("phone_num", user.getPhoneNum());
            qw.orderByDesc("id");
            List<PaySlip> list = paySlipService.getPageEntityList(qw, pageIndex, pageSize);
            map.put("records", list);


            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功", list.size(), map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  工资条信息列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/paySlip/detail")
    public JSONObject paySlipDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String, Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/paySlip/detail 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int slipId = jsonRequest.containsKey("slipId") ? jsonRequest.getInt("slipId") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            PaySlip paySlip = paySlipService.getById(slipId);
            if(paySlip!= null){
                if(StrUtil.isNotEmpty(paySlip.getSignImgUrl())){
                    paySlip.setSignImgUrl(imgPrefix + paySlip.getSignImgUrl());
                }
                map.put("paySlip", paySlip);
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功", map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  工资条信息详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/paySlip/last/detail")
    public JSONObject paySlipLastDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String, Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/paySlip/list 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            QueryWrapper<PaySlip> qw = new QueryWrapper<>();
            qw.eq("phone_num", user.getPhoneNum());
            qw.eq("state", 0);
            qw.last("limit 1");
            PaySlip paySlip = paySlipService.getOne(qw);
            if(paySlip!= null){
                if(StrUtil.isNotEmpty(paySlip.getSignImgUrl())){
                    paySlip.setSignImgUrl(imgPrefix + paySlip.getSignImgUrl());
                }
                map.put("paySlip", paySlip);
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功", map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  添加日志
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add/work/log")
    public JSONObject addWorkLog(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String, Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/user/list 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int parent_id = jsonRequest.containsKey("parent_id") ? jsonRequest.getInt("parent_id") : 0;
            String content = jsonRequest.containsKey("content") ? jsonRequest.getStr("content") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }

            EstateWorkLog workLog = new EstateWorkLog();
            workLog.setUserId(user_id);
            workLog.setParentId(parent_id);
            workLog.setLogType(0);
            if(parent_id > 0){
                workLog.setLogType(1);
            }
            workLog.setEstateId(sysUser.getEstateId());
            workLog.setContent(content);
            workLog.setCreateTime(new Date());
            workLog.setDeptId(sysUser.getDeptId());
            workLog.setName(sysUser.getNickName());
            workLog.setPropertyId(sysUser.getPropertyId());
            workLog.setSysUserId(sysUser.getUserId());
            boolean bl = estateWorkLogService.save(workLog);
            if(bl){
                QueryWrapper<EstateWorkLog> qwAppraise = new QueryWrapper<>();
                qwAppraise.eq("parent_id", parent_id);
                qwAppraise.eq("log_type", 1);
                List<EstateWorkLog> appraiseList = estateWorkLogService.list(qwAppraise);
                map.put("appraises", appraiseList);
                map.put("appraiseCount", appraiseList.size());
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"提交成功", map),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"提交失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  添加日志(已读)
     * @param
     * @throws Exception
     */
    @PostMapping(value="/work/log/read")
    public JSONObject readLog(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String, Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/work/log/read 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int parent_id = jsonRequest.containsKey("parent_id") ? jsonRequest.getInt("parent_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }

            EstateWorkLog workLog = new EstateWorkLog();
            workLog.setUserId(user_id);
            workLog.setParentId(parent_id);
            workLog.setLogType(2);
            workLog.setEstateId(sysUser.getEstateId());
            workLog.setContent("已读");
            workLog.setCreateTime(new Date());
            workLog.setDeptId(sysUser.getDeptId());
            workLog.setName(sysUser.getNickName());
            workLog.setPropertyId(sysUser.getPropertyId());
            workLog.setSysUserId(sysUser.getUserId());

            boolean bl = estateWorkLogService.save(workLog);
            if(bl){
                QueryWrapper<EstateWorkLog> qwAppraise = new QueryWrapper<>();
                qwAppraise.eq("parent_id", parent_id);
                qwAppraise.eq("log_type", 2);
                List<EstateWorkLog> appraiseList = estateWorkLogService.list(qwAppraise);
                map.put("likes", appraiseList);
                map.put("likeCount", appraiseList.size());
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"提交成功", map),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"提交失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  我的日志列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/work/log/list")
    public JSONObject workLogList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/user/list 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;
            int is_manager = jsonRequest.containsKey("is_manager") ? jsonRequest.getInt("is_manager") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }

            SysDept sysDept = sysDeptService.findById(sysUser.getDeptId());
            if(sysDept  == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }

            if(sysDept.getIsOpenLog() == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }

            map.put("is_test_user", user.getIsTestUser());


            Map<String, Object> mapParam = new HashMap<>();
            mapParam.put("log_type", 0);
            mapParam.put("is_del", 0);
            mapParam.put("log_level", sysDept.getLogLevel());
            mapParam.put("property_id", sysUser.getPropertyId());

            QueryWrapper<EstateWorkLog> qw = new QueryWrapper<>();
            if(sysUser.getPropertyId() != null){
                qw.eq("property_id", sysUser.getPropertyId());
            }
            qw.eq("log_type", 0);
            qw.eq("is_del", 0);
            if(user.getIsTestUser() == 0){
                if(is_manager == 0){
                    qw.eq("user_id", user_id);
                    mapParam.put("user_id", user_id);
                }else{
//                    qw.eq("dept_id", sysUser.getDeptId());
                }
            }
            qw.orderByDesc("create_time");

            int offset = (pageIndex - 1) * pageSize;

            List<EstateWorkLog> workLogList = estateWorkLogService.getListByLogLevel(mapParam, offset, pageSize);
            if(CollUtil.isNotEmpty(workLogList)){
                for (EstateWorkLog log : workLogList){
                    log.setIsMain(0);
                    Estate estate = estateService.findById(log.getEstateId());
                    if(estate != null){
                        log.setEstateName(estate.getEstateName());
                    }
                    if(user_id == log.getUserId().intValue()){
                        log.setIsMain(1);
                    }

                    log.setIsRead(0);
                    QueryWrapper<EstateWorkLog> qwRead = new QueryWrapper<>();
                    qwRead.eq("parent_id", log.getId());
                    qwRead.eq("log_type", 2);
                    qwRead.eq("user_id", user_id);
                    qwRead.last("limit 1");
                    EstateWorkLog read = estateWorkLogService.getOne(qwRead);
                    if(read!= null){
                        log.setIsRead(1);
                    }

                    QueryWrapper<EstateWorkLog> qwAppraise = new QueryWrapper<>();
                    qwAppraise.eq("parent_id", log.getId());
                    qwAppraise.eq("log_type", 1);
                    List<EstateWorkLog> appraiseList = estateWorkLogService.list(qwAppraise);
                    log.setAppraiseCount(appraiseList.size());
                    log.setAppraiseList(appraiseList);
                }
            }
            map.put("logList", workLogList);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"提交成功",workLogList.size(), map), false, false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  删除日志
     * @param
     * @throws Exception
     */
    @PostMapping(value="/delete/work/log")
    public JSONObject deleteWorkLog(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/delete/work/log 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int log_id = jsonRequest.containsKey("log_id") ? jsonRequest.getInt("log_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            EstateWorkLog workLog = estateWorkLogService.findById(log_id);
            if(workLog == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该日志不存在"),true,true);
            }

            if(workLog.getUserId().intValue() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"不是您的日志不能删除"),true,true);
            }

            workLog.setIsDel(1);
            workLog.setDeleteTime(new Date());
            boolean bl = estateWorkLogService.updateById(workLog);
            if(bl){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"提交成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"提交失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  上传图片
     * @param
     * @throws Exception
     */
    @PostMapping(value="/paySlip/uploadSignImg")
    @ResponseBody
    public JSONObject uploadImg(@RequestParam("user_id") int user_id,@RequestParam("slip_id") int slip_id, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("slip_id==" + slip_id);

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "该用户不存在"), true, true);
            }

            PaySlip paySlip = paySlipService.getById(slip_id);
            if(paySlip == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "该工资条不存在"), true, true);
            }

            if(!user.getPhoneNum().equals(paySlip.getPhoneNum())){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "不能操作其他人的工资条"), true, true);
            }

            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();

                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "pay_slip_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_PAYSLIP;
                                        String img_key = OssUtil.getUploadPrefix(upload_type) + DateUtil.getSdfYearDay() + "/" + fileName;

                                        String path = uploadPath + OssUtil.getUploadPrefix(upload_type) + DateUtil.getSdfYearDay() ;
                                        System.out.println("path: " + path);
                                        File file = new File(path);
                                        if (!file.exists() && !file.isDirectory()) {
                                            file.mkdirs();
                                        }


                                        String filePath =  path +"/" + fileName;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();

                                        ImagesFiler.imageResize(filePath,filePath);
                                        paySlip.setSignTime(new Date());
                                        paySlip.setState(1);//状态 0-未确认  1-已确认  2-取消确认
                                        paySlip.setSignImgUrl(img_key);
                                        boolean bl = paySlipService.updateById(paySlip);
                                        if(bl){
                                            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "签名成功"), true, true);
                                        }else{
                                            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "签名失败"), true, true);
                                        }
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }
}
